//
//  MainViewController.swift
//  AntProj
//
//  Created by 陈宇 on 2017/5/2.
//  Copyright © 2017年 🐜. All rights reserved.
//

import UIKit
import RxSwift
import RxCocoa
//import GoogleMaps
import MapKit
import CoreLocation
import Haneke
import FSPagerView
import YNDropDownMenu
import SwifterSwift
import SnapKit

class MapViewController: BaseViewController {
    
    @IBOutlet weak var bannerView: FSPagerView! {
        didSet {
            self.bannerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        }
    }
    
    @IBOutlet weak var mapView: MKMapView! {
        didSet {
            mapView.showsUserLocation = true
        }
    }
    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.hideEmpty()
            tableView.rowHeight = 100
            tableView.separatorStyle = .none
            tableView.register(nib: UINib(nibName: "HouseCell", bundle: nil), withCellClass: HouseCell.self)
        }
    }
    @IBOutlet weak var btn_posted: UIButton!
    
    lazy var filterMenu: YNDropDownMenu = {
        let filterViews = Bundle.main.loadNibNamed("MapFilterDropDownViews", owner: nil, options: nil) as? [UIView]
        guard let _filterViews = filterViews else {
            fatalError("没有发现筛选试图")
        }
        
        let menu: YNDropDownMenu = YNDropDownMenu(frame: CGRect(x: 0, y: -39, width: Screen.width, height: 39), dropDownViews: _filterViews, dropDownViewTitles: ["风格", "价格", "排序"])
        menu.setImageWhen(normal: UIImage(named: "arrow_nor"), selected: UIImage(named: "arrow_nor")?.tint(with: APP.APP_PRIMARY_COLOR), disabled: nil)
        menu.setLabelColorWhen(normal: UIColor.black, selected: APP.APP_PRIMARY_COLOR, disabled: UIColor.lightGray)
        menu.setLabel(font: UIFont.systemFont(ofSize: 13))
        
        let backgroundView = UIView()
        backgroundView.backgroundColor = .black
        menu.blurEffectView = backgroundView
        menu.blurEffectViewAlpha = 0.2
        return menu
    }()
    
    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.delegate = self
        searchBar.placeholder = "输入地址、房源编号".localized()
        searchBar.textField?.font = UIFont.systemFont(ofSize: 13)
        return searchBar
    }()
    
    lazy var btn_mode: UIButton = {
        let mode = UIButton()
        mode.setImage(UIImage(named: "mode.list"), for: .normal)
        mode.setImage(UIImage(named: "mode.map"), for: .selected)
        mode.sizeToFit()
        return mode
    }()
    let item_msg = UIBarButtonItem(image: UIImage(named: "map.message"), style: .plain, target: nil, action: nil)
    
    override func configureLeftItem() {
        
        navigationItem.titleView = searchBar
        addLeftBarButtonWithImage(#imageLiteral(resourceName:"menu"))
        navigationItem.rightBarButtonItems = [item_msg, UIBarButtonItem(customView: btn_mode)]
    }
    
    override func configureUI() {
        super.configureUI()
        
        view.addSubview(filterMenu)
    }
    
    override func configureEvent() {
        GeolocationService.instance.location.asObservable().take(1).subscribe(onNext: { [weak mapView] (location) in
            mapView?.setRegion(MKCoordinateRegion(center: location, span: MKCoordinateSpan(latitudeDelta: 0.07, longitudeDelta: 0.07)), animated: true)
        }).addDisposableTo(disposeBag)
        btn_posted.rx.tap.bind {
            log.info("posted")
            }.addDisposableTo(disposeBag)
        btn_mode.rx.tap.bind {
            self.btn_mode.isSelected = !self.btn_mode.isSelected
            self.tableView.isHidden = !self.btn_mode.isSelected
            log.info("mode changed")
            }.addDisposableTo(disposeBag)
        item_msg.rx.tap.bind {
            log.info("msg")
            }.addDisposableTo(disposeBag)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        guard self.filterMenu.y <= 0 else {
            return
        }
        
        self.filterMenu.y = self.mapView.superview!.y - self.filterMenu.height
    }
}

extension MapViewController: MKMapViewDelegate {
    
}

extension MapViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        UIApplication.whisper(title: "搜索房源".localized())
    }
}

extension MapViewController: UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 10
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: HouseCell.self)!
        cell.coverView.hnk_setImageFromURL(APP.APP_PLACEHOLDER_URL, format: Format(name: "cell"))
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 5 : 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 5
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        show(HouseDetailViewController(), sender: tableView)
    }
}

extension MapViewController: FSPagerViewDataSource, FSPagerViewDelegate {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return 3
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
        cell.imageView?.hnk_setImageFromURL(APP.APP_PLACEHOLDER_URL, format: Format(name: "cell"))
        return cell
    }
    
}

